package se.gtg.einstein;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class DoubletsActivity extends Activity implements OnItemClickListener,OnClickListener{
	int position;
	String name;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.doubleslist);
		
		TextView textView = (TextView) findViewById(R.id.choose);
		ListView listView = (ListView) findViewById(R.id.listView);
		Button ok = (Button) findViewById(R.id.ok);
		EcoApp ecoApp = (EcoApp) getApplicationContext();
		SearchLists lists = ecoApp.getSearchLists();
		SearchList doublets = lists.nextSearchListWithDoublets();
		int textViewResourceId = android.R.layout.simple_list_item_1;
		
		ArrayList<String> arrayList = new ArrayList<String>();
		for (SearchList.SearchRecord searchRecord: doublets.getSearchListArray()) {
			arrayList.add(searchRecord.getPresentation());
		}
		ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, textViewResourceId, arrayList);
		listView.setAdapter(arrayAdapter);
		name = doublets.getSearchWord().toString();
		textView.setText("Välj " + name + ":");
		listView.setOnItemClickListener(this);
		ok.setOnClickListener(this);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		parent.setSelection(position);
		view.setSelected(true);
		this.position = position;
	}

	@Override
	public void onClick(View v) {
		EcoApp ecoapp =(EcoApp) getApplicationContext();
		SearchList searchList = ecoapp.getSearchLists().getCurrentSearchList();

		ListView listView = (ListView) findViewById(R.id.listView);
		ArrayAdapter arrayAdapter =(ArrayAdapter) listView.getAdapter();
		String item =(String) arrayAdapter.getItem(position);
		
		SearchList.SearchRecord searchRecord = searchList.getSearchRecordByPresentation(item);
		
		SearchList newSearchList = new SearchList(name);
		newSearchList.add(searchRecord);
		ecoapp.getSearchLists().setCurrentSearchList(newSearchList);
		
		if (ecoapp.getSearchLists().hasMoreSearchListWithDoublets()){
			Intent doublets = new Intent(this,DoubletsActivity.class);
			this.startActivity(doublets);
		}else{
			Intent showResult = new Intent(this,ShowResultActivity.class);
			this.startActivity(showResult);
		}
	}
}
